﻿using System;
using System.Collections.Generic;
using RamGecXNAControls;
using Fusion;
using Fusion.Management;
using RamGecXNAControls.ExtendedControls;
using Microsoft.Xna.Framework;
using Fusion.Content;
using Lidgren.Network;
using EclipseLib.Shared;
using System.Text.RegularExpressions;
using System.Globalization;

namespace Client.Game_States.Game_GUI_s
{
    public class RegMenuGUI
    {
        // Data Members
        public GUIManager RegManager;
        public Window RegWindow;
        public Button RegisterButton;
        public Button MainMenuButton;
        public TextBox UserBox;
        public TextBox PassBox;
        public TextBox PassAgainBox;
        public TextBox EmailBox;
        private MessageBox ErrorMessage;
        private GameTexture BorderShadow;
        private bool invalid;

        // Constructor
        public RegMenuGUI()
        {
            RegManager = new GUIManager(FusionGame.MainGame, "Themes", "Default");
            RegManager.LoadControls(@"Content\Menus\Registration.mnu");

            RegWindow = (Window)RegManager.GetControl("WndRegistration");
            RegisterButton = (Button)RegManager.GetControl("BtnRegister");
            MainMenuButton = (Button)RegManager.GetControl("BtnMainMenu");
            UserBox = (TextBox)RegManager.GetControl("TxtUser");
            PassBox = (TextBox)RegManager.GetControl("TxtPassword");
            PassAgainBox = (TextBox)RegManager.GetControl("TxtPassAgain");
            EmailBox = (TextBox)RegManager.GetControl("TxtEmail");

            RegWindow.Bounds.Location = new Point(640 - (RegWindow.Bounds.Width >> 1), 360 - (RegWindow.Bounds.Height >> 1));
            RegWindow.Movable = false;

            RegisterButton.OnClick += new GUIControl.ClickEventHandler(RegisterClick);
            MainMenuButton.OnClick += new GUIControl.ClickEventHandler(MainMenuClick);

            BorderShadow = GFXHelper.LoadInterfaceTexture(@"BorderShade");
        }

        // Methods
        public void Update()
        {
            RegManager.Update(FusionGame.CurrentTime);
        }
        public void Render()
        {
            FCanvas.Draw(BorderShadow, new Vector2(0, 620), Color.White);
            FCanvas.Draw(BorderShadow, Vector2.Zero, BorderShadow.Texture.Bounds, Color.White, 0f, Vector2.Zero, 1f, Microsoft.Xna.Framework.Graphics.SpriteEffects.FlipVertically, 1f);
            RegManager.Draw(FCanvas.Batch);
        }
        public void Dispose()
        {
            RegManager.Controls.Clear();
            BorderShadow.Release();
        }
        public void ShowError(string Message)
        {
            ErrorMessage = new MessageBox(RegManager, Message);
            ErrorMessage.ButtonIcon = RegManager.Theme.IconWarning;
            ErrorMessage.Show();
        }
        
        public bool IsValidEmail(string strIn)
        {
            invalid = false;
            if (String.IsNullOrEmpty(strIn))
                return false;

            // Use IdnMapping class to convert Unicode domain names. 
            try
            {
                strIn = Regex.Replace(strIn, @"(@)(.+)$", DomainMapper, RegexOptions.None);
            }
            catch
            {
                return false;
            }

            if (invalid)
                return false;

            // Return true if strIn is in valid e-mail format. 
            try
            {
                return Regex.IsMatch(strIn,
                      @"^(?("")(""[^""]+?""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" +
                      @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9]{2,17}))$",
                      RegexOptions.IgnoreCase);
            }
            catch
            {
                return false;
            }
        }
        private string DomainMapper(Match match)
        {
            // IdnMapping class with default property values.
            IdnMapping idn = new IdnMapping();

            string domainName = match.Groups[2].Value;
            try
            {
                domainName = idn.GetAscii(domainName);
            }
            catch (ArgumentException)
            {
                invalid = true;
            }
            return match.Groups[1].Value + domainName;
        }

        // Control Methods
        private void RegisterClick(GUIControl Sender)
        {
            if (UserBox.Text.Length == 0 || PassBox.Text.Length == 0 || EmailBox.Text.Length == 0)
            {
                ShowError("Please fill out the entire form.");
                return;
            }
            else if (!IsValidEmail(EmailBox.Text))
            {
                ShowError("Invalid Email!");
                return;
            }
            else if (PassBox.Text != PassAgainBox.Text)
            {
                ShowError("Passwords do not match!");
                return;
            }

            NetOutgoingMessage Packet = Network.CreatePacket();
            Packet.Write((Int32)ClientPackets.SendNewRegistration);
            Packet.Write(UserBox.Text);
            Packet.Write(PassBox.Text);
            Packet.Write(EmailBox.Text);
            Network.SendData(Packet);
        }
        private void MainMenuClick(GUIControl Sender)
        {
            FStates.ChangeState(new MainMenu(), false);
        }
    }
}
